package com.lamer.console.base.service.impl;

import com.lamer.console.base.entity.Role;
import com.lamer.console.base.entity.User;
import com.lamer.console.base.entity.UserDetailsImpl;
import com.lamer.console.base.service.IRoleService;
import com.lamer.console.base.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(username);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Role> roleList = roleService.getRoleListByUserId(user.getId());
        String authorityString = roleList.stream().map(Role::getRoleNameEN).collect(Collectors.joining(","));
        return new UserDetailsImpl(user, AuthorityUtils.commaSeparatedStringToAuthorityList(authorityString));
    }
}
